//
//  ZHPlugin.m
//  ZHPlugin
//
//  Created by YeQing on 2021/1/22.
//

#import "ZHPlugin.h"
#import <UIKit/UIKit.h>
#import <BCFoundation/BCSwizzle.h>
#import <ZHToastKit/ZHToastKit.h>

/// 原始 bundle id
static NSString * ZHOriginBundleId = @"com.taou.NeiTui";

@interface ZHPlugin()
@end

@implementation ZHPlugin

//MARK: - life cycle
static ZHPlugin *ZHPluginShareInstance = nil;
+ (void)load {
    [[ZHPlugin shared] start];
}
+ (ZHPlugin *)shared {
    @synchronized (self) {
        if(!ZHPluginShareInstance){
            ZHPluginShareInstance = [[ZHPlugin alloc] init];
        }
    }
    return ZHPluginShareInstance;
}

//MARK: - 开始
- (void)start {
    NSLog(@"start hook");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [ZHToastManager showToast:@"hook"];
    });
    BCSwizzleInstanceMethod([UIViewController class], BCHookSelector(@"viewDidLoad"), BCSWReturnType(void), BCSWArguments(), BCSWReplacement({
        [self bczh_viewDidLoad:selfObj];
        BCSWCallOriginal();
    }));
    // 修改 bundle id
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        BCSwizzleInstanceMethod([NSBundle class], BCHookSelector(@"bundleIdentifier"), BCSWReturnType(NSString *), BCSWArguments(), BCSWReplacement({
            if (selfObj == NSBundle.mainBundle) {
                return ZHOriginBundleId;
            }
            else {
                return BCSWCallOriginal();
            }
        }));
        NSLog(@"bundleId:%@",[NSBundle.mainBundle bundleIdentifier]);
        NSLog(@"bundleId:%@",NSBundle.mainBundle.infoDictionary[@"CFBundleIdentifier"]);
        NSLog(@"bundleId:%@",[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleIdentifier"]);
    });
    BCSwizzleInstanceMethod([NSDictionary class], BCHookSelector(@"valueForKey:"), BCSWReturnType(id), BCSWArguments(id key), BCSWReplacement({
        NSString *result = BCSWCallOriginal(key);
        if ([result isKindOfClass:[NSString class]] && [result isEqualToString:@"com.zhihan.faq"]) {
            return ZHOriginBundleId;
        }
        return result;
    }));
    BCSwizzleInstanceMethod([NSDictionary class], BCHookSelector(@"objectForKey:"), BCSWReturnType(id), BCSWArguments(id key), BCSWReplacement({
        NSString *result = BCSWCallOriginal(key);
        if ([result isKindOfClass:[NSString class]] && [result isEqualToString:@"com.zhihan.faq"]) {
            return ZHOriginBundleId;
        }
        return result;
    }));
    BCSwizzleInstanceMethod([NSDictionary class], BCHookSelector(@"objectForKeyedSubscript:"), BCSWReturnType(id), BCSWArguments(id key), BCSWReplacement({
        NSString *result = BCSWCallOriginal(key);
        if ([result isKindOfClass:[NSString class]] && [result isEqualToString:@"com.zhihan.faq"]) {
            return ZHOriginBundleId;
        }
        return result;
    }));
    BCSwizzleInstanceMethod([NSBundle class], BCHookSelector(@"objectForInfoDictionaryKey:"), BCSWReturnType(id), BCSWArguments(id key), BCSWReplacement({
        NSString *result = BCSWCallOriginal(key);
        if (selfObj == NSBundle.mainBundle && [result isKindOfClass:[NSString class]] && [result isEqualToString:@"com.zhihan.faq"]) {
            return ZHOriginBundleId;
        }
        return result;
    }));
//    NSLog(@"bundleId:%@",[NSBundle.mainBundle bundleIdentifier]);
//    NSLog(@"bundleId:%@",NSBundle.mainBundle.infoDictionary[@"CFBundleIdentifier"]);
//    NSLog(@"bundleId:%@",[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleIdentifier"]);
}


//MARK: - hook
-(BOOL)enableSwizzle:(id )obj {
    id enableSwizzle = objc_getAssociatedObject(obj, @selector(enableSwizzle:));
    if (enableSwizzle == nil) {
        //判断是否可以swizzle
        BOOL zh_canSwizle = YES;
        NSString *selfClass = NSStringFromClass([self class]);
        NSArray *classList = [selfClass componentsSeparatedByString:@"."];
        if (classList.count>1) {
            //兼容swift class: target.XXxxVC
            selfClass = classList.lastObject;
        }
        if([selfClass hasPrefix:@"UI"] || [selfClass hasPrefix:@"_UI"]  || [selfClass hasPrefix:@"_SFAppPassword"] || [selfClass hasPrefix:@"SFPassword"]  || [selfClass hasPrefix:@"CKSMS"] || [selfClass hasPrefix:@"CAM"] || [selfClass hasPrefix:@"PUUI"] || [selfClass hasPrefix:@"PUPhoto"] || [selfClass hasPrefix:@"PLPhoto"] || [selfClass hasPrefix:@"GS"] || [selfClass hasPrefix:@"Vod"] || [selfClass hasPrefix:@"AVPlayer"] || [selfClass hasPrefix:@"AVFullScreen"]){
            //CAM 开头：拍照库 ，PUUI：相册库，PLPhoto：相册编辑，CKSMS：短信page
            //GS,Vod 互动课堂SDK
            zh_canSwizle = NO;
        }
        else if([self isKindOfClass:[UITabBarController class]]) {
            zh_canSwizle = NO;
        }
        else if([self isKindOfClass:[UINavigationController class]]) {
            zh_canSwizle = NO;
        }
        objc_setAssociatedObject(obj, @selector(enableSwizzle:), @(zh_canSwizle), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        return zh_canSwizle;
    }
    return [enableSwizzle boolValue];
}
- (void)bczh_viewDidLoad:(id )obj {
    if (![self enableSwizzle:obj]) {
        return;
    }
    NSLog(@"[hook] %@ load",NSStringFromClass([obj class]));
}
@end
